//
//  HBHLoginViewController.m
//  HubeiHotel
//
//  Created by 张露杰 on 17/11/7.
//  Copyright © 2017年 张露杰. All rights reserved.
//

#import "HBHLoginViewController.h"
#import "HBHTabBarViewController.h"
#import "HBHDLoginTextFild.h"

@interface HBHLoginViewController ()
@property (nonatomic,strong)NSTimer *timer;//定时器
@property (nonatomic,assign)int s;//秒
@property (nonatomic,strong)UIButton *sendBtn;//验证码按钮
@property (nonatomic,strong)NSString *phoneStr;//手机号
@property (nonatomic,strong)NSString *passWordStr;//手机号

@property (nonatomic, strong) TencentOAuth *tencentOAuth;
@end

@implementation HBHLoginViewController

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = YES;
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    self.navigationController.navigationBarHidden = NO;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self creatView];
}

-(void)creatView
{
    UIImageView *imageV = [TomamaUI createImageView:CGRectMake(0, 0, SCREENW, SCREENH) backGroundImageV:@"Login_back"];
    [self.view addSubview:imageV];
    
    UIImageView *logoImageV = [TomamaUI createImageView:CGRectMake(0, 110*screenW_6, 62*screenW_6, 92*screenW_6) backGroundImageV:@"Login_logo"];
    [self.view addSubview:logoImageV];
    logoImageV.center = CGPointMake(SCREENW/2, logoImageV.center.y);
    
    //手机号
    HBHDLoginTextFild *phoneView = [[HBHDLoginTextFild alloc]initWithFrame:CGRectMake(30*screenW_6, CGRectGetMaxY(logoImageV.frame) + 54*screenW_6, 0, 0) imageName:@"Login_phone" placeholder:@"手机号" keyboardType:UIKeyboardTypeNumberPad maxNum:11];
    phoneView.CCSDLoginTextFildblock = ^(NSString *text){
        _phoneStr = text;
    };
    [self.view addSubview:phoneView];
    
    //发送验证码
    _sendBtn = [TomamaUI createButton:0 Frame:CGRectMake(SCREENW-70*screenW_6,CGRectGetMaxY(logoImageV.frame) + 60*screenW_6,40*screenW_6, 45*screenW_6) targ:self sel:@selector(sengMessage) titleColor:[UIColor whiteColor] font:[UIFont systemFontOfSize:16*screenW_6] title:@"发送" image:nil backGroundImage:nil];
    [self.view addSubview:_sendBtn];
//    sendBtn.backgroundColor = [UIColor colorWithHexString:@"#edf8fa"];
//    sendBtn.layer.masksToBounds = YES;
//    sendBtn.layer.cornerRadius = 3;
    
    //验证码
    HBHDLoginTextFild *msgView = [[HBHDLoginTextFild alloc]initWithFrame:CGRectMake(30*screenW_6, CGRectGetMaxY(phoneView.frame), 0, 0) imageName:@"Login_msg" placeholder:@"验证码" keyboardType:UIKeyboardTypeNumberPad maxNum:6];
    msgView.CCSDLoginTextFildblock = ^(NSString *text){
        _passWordStr = text;
    };
    [self.view addSubview:msgView];

    //登陆
    UIButton *loginBtn = [TomamaUI createButton:0 Frame:CGRectMake(30*screenW_6, CGRectGetMaxY(msgView.frame) + 40*screenW_6, SCREENW - 60*screenW_6, 45*screenW_6) targ:self sel:@selector(goToLogin) titleColor:[UIColor colorWithHexString:@"#4cb8c7"] font:[UIFont systemFontOfSize:16*screenW_6] title:@"进入湖北酒店网" image:nil backGroundImage:nil];
    [self.view addSubview:loginBtn];
    loginBtn.backgroundColor = [UIColor colorWithHexString:@"#edf8fa"];
    loginBtn.layer.masksToBounds = YES;
    loginBtn.layer.cornerRadius = 3;
    
    
    UILabel *thirdLabel = [TomamaUI createLabel:CGRectMake(0, CGRectGetMaxY(loginBtn.frame) + 52*screenW_6, SCREENW, 14*screenW_6) textAligment:1 font:[UIFont systemFontOfSize:14*screenW_6] textColor:[UIColor colorWithHexString:@"#AADDE4"] text:@"第三方登录"];
    [self.view addSubview:thirdLabel];
    
    UIImageView *lineImageV = [TomamaUI createImageView:CGRectMake(0, 0 , SCREENW, .5) backGroundImageV:@"Login_line"];
    [self.view addSubview:lineImageV];
    lineImageV.center = CGPointMake(lineImageV.center.x, thirdLabel.center.y);
    
    UIButton *wecharBtn = [TomamaUI createButton:0 Frame:CGRectMake(120*screenW_6, CGRectGetMaxY(thirdLabel.frame) + 23*screenW_6, 42*screenW_6, 42*screenW_6) targ:self sel:@selector(loginWechar) titleColor:nil font:nil title:nil image:@"Login_wechar" backGroundImage:nil];
    [self.view addSubview:wecharBtn];
    
    if ([TencentOAuth iphoneQQInstalled]) {
        UIButton *qqBtn = [TomamaUI createButton:0 Frame:CGRectMake(CGRectGetMaxX(wecharBtn.frame) + 45*screenW_6, CGRectGetMaxY(thirdLabel.frame) + 23*screenW_6, 42*screenW_6, 42*screenW_6) targ:self sel:@selector(loginQQ) titleColor:nil font:nil title:nil image:@"Login_qq" backGroundImage:nil];
        [self.view addSubview:qqBtn];
    }
    
    UILabel *label = [TomamaUI createLabel:CGRectMake(0, SCREENH - 30*screenW_6, SCREENW, 12*screenW_6) textAligment:1 font:[UIFont systemFontOfSize:12*screenW_6] textColor:[UIColor colorWithHexString:@"#2c85a3"] text:@"点击进入湖北酒店网即表示同意《湖北酒店网使用协议》"];
    [self.view addSubview:label];
    UIButton *btn = [TomamaUI createButton:0 Frame:CGRectMake(SCREENW - 45*screenW_6, 21, 44*screenW_6, 44*screenW_6) targ:self sel:@selector(dissMiss) titleColor:nil font:nil title:nil image:@"Login_dismiss" backGroundImage:nil];
    [self.view addSubview:btn];
}

-(void)dissMiss
{
    [self dismissViewControllerAnimated:YES completion:nil];
}


//登陆
-(void)goToLogin
{
    [HudHelper showProgressHudWithMessage:@"" toView:self.view];
    if (_phoneStr.length!=11) {
        [HudHelper hideHudToView:self.view];
        [TomamaUI creatAlertWithTarget:self message:@"请正确填写手机号" timeInterval:2];
        return;
    }
    if ( _passWordStr.length<6) {
        [HudHelper hideHudToView:self.view];
        [TomamaUI creatAlertWithTarget:self message:@"验证码不能小于6位" timeInterval:2];
        return;
    }
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        [HttpRequest PostrequestUrl:@"/login" Dic:@{ @"phone":_phoneStr,@"verificationCode":_passWordStr}completion:^(NSDictionary *responseDic)
         {
             dispatch_async(dispatch_get_main_queue(), ^{
                 [HudHelper hideHudToView:self.view];
                 if ([responseDic[@"success"] boolValue]) {//请求成功
                     NSMutableDictionary *dic = [[NSMutableDictionary alloc]initWithDictionary:responseDic[@"data"]];
                     [standfault setObject:dic forKey:@"userInfo"];
                     [standfault synchronize];
                     appDelegate.window.rootViewController = [HBHTabBarViewController new];;
                     
                 }else//请求失败提示
                 {
                     [ToolViewVC addKeyAlterViewController:responseDic[@"msg"]?responseDic[@"msg"]:@"登录失败" Controller:self];
                 }
             });
         }];
    });
}
//qq第三方登录
-(void)loginQQ
{
    _tencentOAuth = [[TencentOAuth alloc] initWithAppId:QQKey andDelegate:self];
    _tencentOAuth.authShareType = AuthShareType_QQ;//特别要注意，登录前需要授权，否则会爆出未授权错误（多看文档还是有好处的哈）
    NSArray *permissions = [NSArray arrayWithObjects:@"get_user_info",@"get_simple_userinfo", @"add_t", nil];
    [_tencentOAuth authorize:permissions];
}
//微信第三方登录
-(void)loginWechar
{
    [TomamaUI creatAlertWithTarget:self message:@"敬请期待" timeInterval:2];
}

-(void)sengMessage//发送验证码
{
    _sendBtn.userInteractionEnabled = NO;
    if (_phoneStr.length==11) {//手机验证11位
        _s = 60;
        [_sendBtn setTitle:@"60秒" forState:UIControlStateNormal];
        _sendBtn.titleLabel.font = [UIFont systemFontOfSize:14];
        _timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(onTimer) userInfo:nil repeats:YES];
        [HttpRequest PostrequestUrl:@"/login/loginSendverificationCode" Dic:
         @{@"phone":_phoneStr,
          } completion:^(NSDictionary *responseDic) {
               if (![responseDic[@"success"] boolValue]) {//请求失败 重置定时器 及按钮
                   [HudHelper showHudWithMessage:responseDic[@"msg"]?responseDic[@"msg"]:@"验证码发送失败" toView:self.view];
                   [_sendBtn setTitle:@"发送" forState:UIControlStateNormal];
                   _sendBtn.userInteractionEnabled = YES;
                   [_timer invalidate];
                   _timer = nil;
               }
           }];
    }
    else//验证失败
    {
        [ToolViewVC addKeyAlterViewController:@"手机号码格式不正确" Controller:self];
        _sendBtn.userInteractionEnabled = YES;
    }
}
//定时器
-(void)onTimer
{
    _s--;
    NSString *timeStr = [NSString stringWithFormat:@"%d秒",_s];
    [_sendBtn setTitle:timeStr forState:UIControlStateNormal];
    if (_s==0)//秒数为0 重置按钮定时器
    {
        [_sendBtn setTitle:@"重发验证码" forState:UIControlStateNormal];
        _sendBtn.userInteractionEnabled = YES;
        [_timer invalidate];
        _timer = nil;
    }
}

#pragma mark -- TencentSessionDelegate
- (void)tencentDidLogin
{
    NSLog(@"yes");
    NSLog(@"%@ -- %@",_tencentOAuth.accessToken, _tencentOAuth.openId);// 打印下accessToken和openId 代表我成功了，存储起来用的时候直接用，或者此处请求服务器接口传给服务器，获取我们项目中用到的userSession
    //获取用户个人信息
    [_tencentOAuth getUserInfo];
}

-(void)tencentDidNotLogin:(BOOL)cancelled
{
    
}

-(void)tencentDidNotNetWork
{
    [TomamaUI creatAlertWithTarget:self message:@"网络异常" timeInterval:2];
}

#pragma mark -- 获取用户个人信息
- (void)getUserInfoResponse:(APIResponse*)response
{
    [HudHelper showProgressHudWithMessage:@"" toView:self.view];
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        [HttpRequest PostrequestUrl:@"/login/qquserregist" Dic:@{@"nickName":response.jsonResponse[@"nickname"],@"headPortrait":response.jsonResponse[@"figureurl_2"],@"qqOpenId":_tencentOAuth.openId} completion:^(NSDictionary *responseDic) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [HudHelper hideHudToView:self.view];
                if ([responseDic[@"success"] boolValue]) {//请求成功
                    NSMutableDictionary *dic = [[NSMutableDictionary alloc]initWithDictionary:responseDic[@"data"]];
                    [standfault setObject:dic forKey:@"userInfo"];
                    [standfault synchronize];
//                    appDelegate.window.rootViewController = [HBHTabBarViewController new];
                    [self dismissViewControllerAnimated:YES completion:nil];
                }else//请求失败提示
                {
                    [ToolViewVC addKeyAlterViewController:responseDic[@"msg"]?responseDic[@"msg"]:@"登录失败" Controller:self];
                }
            });
        }];
    });
}

@end
